iT邦幫忙

2025 iThome 鐵人賽

DAY 8
0
自我挑戰組

打造自己的Medium系列 第 8

Day8 Vue + Typescript

  • 分享至 

  • xImage
  •  

開發環境配置

  • IDE: VS Code
  • 基本Plugin: Vue
  • 格式化Plugin: Prettier

建立專案

  1. 建立Vue指令
    npm create vue@latest <my-app-name>
  2. 指令執行後,會出現選項讓你選擇是否使用 Typescript 及其他輔助功能
  3. 可能會需要注意一下當前node的版本是否能搭配:
    • 查看已安裝node: nvm list
    • 查看可安裝node: nvm list available
    • 安裝指定版本node: nvm install <version>

寫法變化

  1. script中新增了lang="ts",使用interface定義參數
<script setup lang="ts">
interface Book {
  title: string
  author: string
  year: number
}

const props = defineProps<{
  book: Book
}>()
</script>
  1. 補充prop,在運行時的資料驗證
import type { PropType } from 'vue'
const props = defineProps({
  book: {
    type: Object as PropType<Book>,
    required: true
  }
})

Vue Router

  1. 指定路徑所使用的頁面
import { createMemoryHistory, createRouter, RouteRecordRaw } from 'vue-router'

import HomeView from './HomeView.vue'
import AboutView from './AboutView.vue'

const routes: RouteRecordRaw[] = [
  { path: '/', component: HomeView },
  { path: '/about', component: AboutView },
]

const router = createRouter({
  history: createMemoryHistory(),
  routes,
})

export default router
  1. 註冊路由
// main.ts
import router from './router'
const app = createApp(App)

app.use(router)

app.mount('#app')

我覺得知道個大概,再來用nuxt

參考資料

  1. Creating a Vue 3 and TypeScript project using Vite
  2. Using Vue with TypeScript
  3. nvm:安裝、切換不同 Node.js 版本的管理器
  4. Vue Router

作者的哈拉

今天也是忙碌的一天,先這樣/images/emoticon/emoticon02.gif


上一篇
Day7 Vue基礎篇(下)
下一篇
Day9 雜談
系列文
打造自己的Medium30
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言